package com.longe.controller;

import com.longe.entity.User;
import com.longe.service.UserService;
import com.longe.util.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @RequestMapping("login")
    public String login(String userName, String password, HttpServletResponse response){

        User user = userService.selectUserByName(userName);

        if(null == user){
            throw new RuntimeException("用户不存在");
        }
        //密码暂时不校验
        /*if(!SecureUtil.md5(password + user.getSalt()).equalsIgnoreCase(user.getPassword())){
            throw new RuntimeException("密码不正确");
        }*/

        Map<String, Object> mapInfo = new HashMap<>();
        mapInfo.put("info", user);
        String token = jwtUtil.createJWT(user.getId().toString(), user.getUserName(), mapInfo);
        response.setHeader("token", token);

        return "home";
    }

    @RequestMapping("logout")
    public String logout(){

        Subject current = SecurityUtils.getSubject();
        current.logout();

        return "/";
    }

    @RequestMapping("test")
    public String haha(){

        return "home";
    }
}
